//
//  LocationCentral.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 11/5/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "LocationCentral.h"
#import "Location.h"
#import	"LocationProfile.h"
#import "JSON/JSON.h" 

#define kViewTag				1		// for tagging our embedded controls for removal at cell recycle time

#define ROW_HEIGHT_FOR_TABLE 30

#define LOCATION_ACCURACY		100.0
#define LOCATION_TIMEOUT		30.0

#define kLatitudeDegrees	.02
#define kLongitudeDegrees	.02

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";


@implementation LocationCentral

@synthesize locationCentralTableView, mapView;
@synthesize nearbyLocationsConnection;
@synthesize nearbyLocations, latitude, longitude;
@synthesize tableSourceArray;
@synthesize locationController, appDelegate;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	self.nearbyLocations = [[NSMutableArray alloc] init];
	self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
	
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Nearby Locations", kSectionTitleKey,
							 self.nearbyLocations, kSourceKey,
							 nil],
							nil];
	
	[self getCurrentLocation];
	[self setupMapView];
	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewDataMethods
- (void)populateNearbyLocations:(NSDictionary *)parsedData{
	//	NSLog(@"Entering populateNearbyLocations\n");
	NSMutableArray *nearbyLocationsArray = [parsedData objectForKey:@"locations"];
	//	NSLog(@"nearbyLocationsArray has %d elements\n", [nearbyLocationsArray count]);
	if([nearbyLocationsArray count] == 0){
		//Do something
	}else{
		[nearbyLocations removeAllObjects];
		int i;
		for(i = 0; i < [nearbyLocationsArray count]; i++){
			//			NSLog(@"creating location for index %d\n", i);
			Location *location = [[Location alloc] init];
			NSDictionary *locationDic = [nearbyLocationsArray objectAtIndex:i];
			location.locationId = [[locationDic objectForKey:@"id"] integerValue];
			location.locationName = [locationDic objectForKey:@"name"];
			location.phoneNumber = [locationDic objectForKey:@"phoneNumber"];
			location.latitude = [[locationDic objectForKey:@"latitude"] doubleValue];
			location.longitude = [[locationDic objectForKey:@"longitude"] doubleValue];
			location.street = [locationDic objectForKey:@"street"];
			location.city = [locationDic objectForKey:@"city"];
			location.state = [locationDic objectForKey:@"state"];
			location.zipCode = [locationDic objectForKey:@"zipcode"];
			location.description = [locationDic objectForKey:@"description"];
			NSDictionary *teamDic = [locationDic objectForKey:@"owner"];
			location.teamOwner = [self populateTeamOwner:(NSDictionary *)teamDic];
			//			NSLog(@"created location that looks like [%d, %@, %f, %f,", location.locationId, location.locationName, location.latitude, location.longitude);
			//			NSLog(@"%@, %@, %@, %@, %@,", location.phoneNumber, location.street, location.city, location.state, location.zipCode);
			//			NSLog(@"%@, {%d, %@}]\n", location.description, location.teamOwner.teamId, location.teamOwner.teamName);
			[nearbyLocations addObject: location];
		}
		//		NSLog(@"nearbyLocations has %d objects", [nearbyLocations count]);
	}
	[self.locationCentralTableView reloadData];
}

- (Team *)populateTeamOwner:(NSDictionary *)teamDic{
	//	NSLog(@"Entering populateTeamOwner\n");
	Team *teamOwner = [[Team alloc] init];
	teamOwner.teamId = [[teamDic objectForKey:@"id"] integerValue];
	teamOwner.teamName = [teamDic objectForKey:@"name"];
	//	NSLog(@"Returning teamOwner that looks like: [%d , %@]\n", teamOwner.teamId, teamOwner.teamName);
	return teamOwner;
}

#pragma mark -
#pragma mark Location Methods

- (void)getCurrentLocation{
	//	NSLog(@"Entering getCurrentLocation\n");
	if(TARGET_IPHONE_SIMULATOR){
		latitude = 33.969326;
		longitude = -118.414387;
		[self getNearbyLocations];
	} else {
		locationController = [[SerengetiCLController alloc] init];
		locationController.delegate = self;
		locationController.locationManager.desiredAccuracy =  LOCATION_ACCURACY;
		[locationController.locationManager startUpdatingLocation];
		[self performSelector:@selector(stopUpdatingLocation:) withObject:@"Timed Out" afterDelay:LOCATION_TIMEOUT];
	}
}

- (void)locationUpdate:(CLLocation *)location {
	//	NSLog(@"Entering locationUpdate.\n");
	//	NSLog(@"location is %@", location);
	//	NSLog(@"location.coordinate.latitude = %f\n", location.coordinate.latitude);
	self.latitude = location.coordinate.latitude;
	//	NSLog(@"self.latitude = %f\n", self.latitude);
	self.longitude = location.coordinate.longitude;	
	[self getNearbyLocations];
}

- (void)locationError:(NSError *)error {
	NSLog(@"Error capturing locaiton: %@", [error description]);
}

- (void)stopUpdatingLocation:(NSString *)state {
	[locationController.locationManager stopUpdatingLocation];
	locationController.locationManager.delegate = nil;
}

- (void)getNearbyLocations{
	//	NSLog(@"Entering getNearbyLocations\n");
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@location/getNearbyLocations?latitude=%f&longitude=%f", appDelegate.baseURL, latitude, longitude];
	//	NSLog(@"String to request nearby locations reads %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	nearbyLocationsConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];		
}

#pragma mark -
#pragma mark mapView methods

- (void) setupMapView {
	NSLog(@"Entering setupMapView");
	NSLog(@"Current lat and long are %f, %f", latitude, longitude);
	mapView.showsUserLocation = YES;
	mapView.mapType = MKMapTypeStandard;
	mapView.delegate = self;
	
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta = kLatitudeDegrees;
	span.longitudeDelta = kLongitudeDegrees;
	
	CLLocationCoordinate2D center;
	center.latitude = latitude;
	center.longitude = longitude;
	region.span = span;
	region.center = center;
	
	NSLog(@"center's lat and long are %f, %f", center.latitude, center.longitude);
	
	[mapView setCenterCoordinate:center animated:YES];
	
	[mapView setRegion:region animated:TRUE];
	[mapView regionThatFits:region];
	[self.view insertSubview:mapView atIndex:0];
	NSLog(@"mapview's center is currently %f, %f", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSLog(@"Connection to nearbyLocations failed: %@\n", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {	
//		NSLog(@"Entering connectionDidFinishLoading with nearbyLocationConenction\n");
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	//		NSLog(@"responseString for nearbyLocationsConnection reads: %@\n", responseString);
	
	[responseData release];
	responseData = nil;
	
	NSDictionary *parsedData = [responseString JSONValue];
	
	[responseString release];
	
	if (parsedData == nil) {
		NSLog(@"Error in returned nearby location data.\n");
	} else {
		[self populateNearbyLocations:(NSDictionary *)parsedData];
	}
}	

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//	NSLog(@"Entering numberOfRowsInSection:%d", section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
	//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
//In this example, each row is determined by its subviews that are embedded.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ROW_HEIGHT_FOR_TABLE;
	//return ([indexPath row] == 0) ? 50.0 : 38.0;
}

// to determine which UITableViewCell to be used on a given row.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = nil;
	Location *aLocation;
	
	aLocation = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.locationCentralTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil){
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	} else {
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	
	cell.textLabel.text = aLocation.locationName;
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	Location *aLocation;
	
	aLocation = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
	LocationProfile *aLocationProfileView = [[LocationProfile alloc] initWithNibName:@"LocationProfile" bundle:nil];
	aLocationProfileView.locationId = aLocation.locationId;
		
//		[aLocation release];
//		aLocation = nil;
		[self.view addSubview:aLocationProfileView.view];
	
}

@end
